import { ref, watchEffect } from 'vue'
import { defineStore } from 'pinia'
import { type RouteLocationNormalized } from 'vue-router'
import store from '@/store'
import {
  getVisitedViews,
  setVisitedViews,
  getCacheViews,
  setCachedViews
} from '@/utils/cache/local-storage'

export type Tab = Partial<RouteLocationNormalized>

export const useTabStore = defineStore(
  'tab',
  () => {
    const visitedViews = ref<Tab[]>(getVisitedViews())
    const cachedViews = ref<string[]>(getCacheViews())

    //缓存标签栏数据
    watchEffect(() => {
      setVisitedViews(visitedViews.value)
      setCachedViews(cachedViews.value)
    })

    const addVisitedView = (tab: Tab) => {
      //检查是否已经存在相同的tab
      const index = visitedViews.value.findIndex((v) => v.path === tab.path)
      if (index !== -1) {
        //防止query 参数丢失
        visitedViews.value[index].fullPath !== tab.fullPath &&
          (visitedViews.value[index] = { ...tab })
      } else {
        //添加新的visitedView
        visitedViews.value.push({ ...tab })
      }
    }

    const addCachedView = (tab: Tab) => {
      if (typeof tab.name !== 'string') return
      if (cachedViews.value.includes(tab.name)) return
      if (tab.meta?.keepAlive) cachedViews.value.push(tab.name)
    }

    const delVisitedView = (tab: Tab) => {
      const index = visitedViews.value.findIndex((v) => v.path === tab.path)
      if (index !== -1) visitedViews.value.splice(index, 1)
    }

    const delCachedView = (tab: Tab) => {
      if (typeof tab.name !== 'string') return
      const index = cachedViews.value.indexOf(tab.name)
      if (index !== -1) cachedViews.value.splice(index, 1)
    }

    const delOthersVisitedViews = (tab: Tab) => {
      visitedViews.value = visitedViews.value.filter((v) => {
        return v.meta?.affix || v.path === tab.path
      })
    }

    const delOthersCachedViews = (tab: Tab) => {
      if (typeof tab.name !== 'string') return
      const index = cachedViews.value.indexOf(tab.name)
      if (index !== -1) {
        cachedViews.value = cachedViews.value.splice(index, index + 1)
      } else {
        // 如果 index = -1, 没有缓存的 tags
        cachedViews.value = []
      }
    }

    const delAllVisitedViews = () => {
      //保留固定的tab
      visitedViews.value = visitedViews.value.filter((v) => v.meta?.affix)
    }
    const delAllCachedViews = () => {
      cachedViews.value = []
    }

    return {
      visitedViews,
      cachedViews,
      addVisitedView,
      addCachedView,
      delVisitedView,
      delCachedView,
      delOthersVisitedViews,
      delOthersCachedViews,
      delAllVisitedViews,
      delAllCachedViews
    }
  },
  {
    persist: true
  }
)

export function useTabStoreHook() {
  return useTabStore(store)
}
